package com.qian.ddj.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kspay.AESUtil;
import com.qian.api.ddj.model.*;
import com.qian.api.ddj.service.*;
import com.qian.api.ddj.util.RSASignUtils;
import com.qian.api.ddj.util.SignUtils;
import com.qian.api.ddj.util.UrlUtils;
import com.qian.ddj.pay.model.Pay;
import com.qian.ddj.pay.model.PlaceOrder;
import com.qian.ddj.pay.model.PlaceOrderV2;
import com.qian.ddj.pay.model.RespBody;
import com.qian.ddj.pay.util.HttpClient;
import com.qian.ddj.pay.util.HttpRequestUtil;
import com.qian.ddj.pay.util.MD5Utils;
import com.qian.ddj.pay.util.XmlUtils;
import com.qian.ddj.pay.util.YLUtils.ApiUtils;
import com.qian.ddj.pay.util.YLUtils.HttpClientUtils;
import com.qian.ddj.pay.util.YLUtils.JsonUtils;
import com.qian.ddj.pay.util.shyqUtil.PayUtils;
import com.yaowk.api.common.BaseException;
import com.yaowk.api.utils.HttpUtils;
import com.yaowk.web.common.adapter.ResponseString;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.qian.ddj.pay.util.YLUtils.ApiUtils.DEFAULT_ENCODING;
import static com.qian.ddj.pay.util.YLUtils.ApiUtils.getSign;

//import com.innovatepay.merchsdk.request.ChinaInPayCodeRequest;
//import com.innovatepay.merchsdk.util.BeanToMapUtil;
//import com.innovatepay.merchsdk.util.HttpClientUtil;
//import com.opentech.cloud.server.component.api.sdk.ApiClient;
//import com.opentech.cloud.server.component.api.sdk.ApiClientFactory;
//import com.opentech.cloud.server.component.api.sdk.ApiRequestBuilder;
//import com.opentech.cloud.server.component.api.sdk.ApiResponse;

@Controller
@Slf4j
@Api("支付接口")
public class PayController {

    private static final String DEFAULT_ENCODING = "UTF-8";
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final Byte PHONE_TYPE = new Byte("1"); // 手机类型
    @Value("${host}")
    private String HOST;

    @Autowired
    private IUserService userService;
    @Autowired
    private IBusinessService businessService;
    @Autowired
    private IBusinessGroupService businessGroupService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IChannelService channelService;
    @Autowired
    private IPayFailedService payFaildService;
    @Autowired
    private ICodeService codeService;
    @Autowired
    private IAliCodeService aliCodeService;
    @Autowired
    private IAliCode2Service aliCode2Service;
    @Autowired
    private IConfigService configService;

    @PostMapping("/v2")
    public String v2(PlaceOrderV2 placeOrder, Model model) {
        System.out.println("invoke v2 method.......");
        if (PayTypeDict.ALL.equals(placeOrder.getPayType())) {
            return index(placeOrder, model);
        }

        model.addAttribute("host", HOST);

        User user = new User();
        user.setUsername(placeOrder.getUser_id());
        user = userService.findOne(user);
        if (!verifyOrder(placeOrder, user, model)) {
            return "err";
        }
        Order order = new Order();
        order.setOutOrderNo(placeOrder.getOutOrderNo());
        order.setUserId(user.getId());
        order.setAmount(placeOrder.getAmount());
        order.setRealAmount(placeOrder.getAmount());
        order.setBody(placeOrder.getOther());
        order.setNotifyUrl(placeOrder.getNotify());
        order.setOrderNo(user.getId() + placeOrder.getOutOrderNo());
        order.setStatus(StatusDict.NORMAL);
        order.setFrontUrl(placeOrder.getFront());
        order.setPayerIp(placeOrder.getIp_address());
        // 保存订单
        order = orderService.save(order);

        Pay pay = new Pay();
        pay.setPayType(placeOrder.getPayType());
        pay.setOrderId(order.getId());
        RespBody respBody = pay(pay);
        if ("-1".equalsIgnoreCase(respBody.getRespCode())) {
            model.addAttribute("error", respBody.getRespInfo());
            return "err";
        }

        model.addAttribute("orderId", order.getId());
        return "payV2";
    }

    @ResponseBody
    @GetMapping("/v2/query/{id}")
    public Byte query(@PathVariable Integer id) {
        Order order = orderService.findById(id);
        return order.getStatus();
    }

    @GetMapping("/v2/selfPay/{id}")
    public String selfPay(@PathVariable Integer id, Model model) {
        Order order = orderService.findById(id);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -4);
        if (order.getCreateTime().getTime() <= calendar.getTimeInMillis()) {
            model.addAttribute("error", "订单已失效");
            return "err";
        }

        if (order.getStatus().equals(StatusDict.SUCCESS_PAY) || order.getStatus().equals(StatusDict.FINISH_PAY) || order.getStatus().equals(StatusDict.SETTLEMENT)) {
            model.addAttribute("error", "订单已完成，请勿重复支付");
            return "err";
        }

        Channel channel = channelService.findChannelByBusinessId(order.getBusinessId());

        String remark = null;
        String codeUrl = null;
        if ("selfZFB".equalsIgnoreCase(channel.getCode())) {
            AliCode aliCode = aliCodeService.findById(order.getCodeId());
            if (aliCode != null) {
                remark = aliCode.getRemark();
                codeUrl = aliCode.getQrCode();
            }
        } else if ("selfZFB2".equalsIgnoreCase(channel.getCode())) {
            AliCode2 aliCode2 = aliCode2Service.findById(order.getCodeId());
            if (aliCode2 != null) {
                remark = aliCode2.getRemark();
                codeUrl = aliCode2.getQrCode();
            }
        }
        if (remark == null || !remark.equalsIgnoreCase(order.getRemark())) {
            model.addAttribute("error", "支付异常，请联系管理员");
            return "err";
        }
        order.setStatus(StatusDict.WAIT_PAY);
        orderService.save(order);
//        response.setHeader("Location", aliCode.getQrCode());
        model.addAttribute("qrcode", codeUrl);
        return "selfPay";
    }

    @ResponseBody
    @GetMapping("/v2/{id}/{deviceType}")
    public Order v2Order(@PathVariable Integer id, @PathVariable Byte deviceType) {
        boolean isPhone = PHONE_TYPE.equals(deviceType);
        Order order = orderService.findById(id);
        BusinessGroup businessGroup = businessGroupService.findByBusinessId(order.getBusinessId());
        Order o = new Order();
        o.setOutOrderNo(order.getOutOrderNo());
        o.setBody(order.getBody());
        o.setAmount(order.getRealAmount());
        o.setCode(order.getCode());
        o.setPayType(order.getPayType());
        o.setFrontUrl(order.getFrontUrl());
        switch (order.getPayType()) {
            case 1:
                if (isPhone && businessGroup.getAllowAliWap().equals(StatusDict.NORMAL)) {
                    order.setPayType(PayTypeDict.ALI_WAP);
                    o.setPayType(PayTypeDict.ALI_WAP);
                }
                break;
            case 4:
                if (isPhone && businessGroup.getAllowQqWap().equals(StatusDict.NORMAL)) {
                    order.setPayType(PayTypeDict.QQ_WAP);
                    o.setPayType(PayTypeDict.QQ_WAP);
                }
                break;
        }

        Channel channel = channelService.findById(businessGroup.getChannelId());
        if ("selfZFB".equalsIgnoreCase(channel.getCode()) || "selfZFB2".equalsIgnoreCase(channel.getCode())) {
            o.setRemark("请在4分钟内完成支付！支付成功后不要重复支付，否则金额无法到账！！！");
//            o.setNotifyMsg("因平台日交易量巨大，请忽视支付宝可能对此进行的风险提示，放心支付。\n如有疑问，请联系平台在线客服！\n亲 祝您游戏愉快！");
        }
        orderService.save(order);
        return o;
    }


    @PostMapping("/")
    @ApiOperation("下单接口")
    public String index(PlaceOrder placeOrder, Model model) {
        String view = "err";
        model.addAttribute("host", HOST);

        User user = new User();
        user.setUsername(placeOrder.getUser_id());
        user = userService.findOne(user);
        if (!verifyOrder(placeOrder, user, model)) {
            return view;
        }

        Set<Byte> allowSet = businessService.findPayTypeByUserId(user.getId());
        if (CollectionUtils.isEmpty(allowSet)) {
            model.addAttribute("error", "没有可用的支付渠道");
            return view;
        }

        Order order = new Order();
        order.setOutOrderNo(placeOrder.getOutOrderNo());
        order.setUserId(user.getId());
        order.setAmount(placeOrder.getAmount());
        order.setRealAmount(placeOrder.getAmount());
        order.setBody(placeOrder.getOther());
        order.setNotifyUrl(placeOrder.getNotify());
        order.setOrderNo(user.getId() + order.getOutOrderNo());
        // 保存订单
        order = orderService.save(order);

        // 寻找可用支付方式
        model.addAttribute("a1", false);
        model.addAttribute("a2", false);
        model.addAttribute("a3", false);
        model.addAttribute("a4", false);
        model.addAttribute("a5", false);
        model.addAttribute("a6", false);
        model.addAttribute("a7", false);
        for (Byte allow : allowSet) {
            model.addAttribute("a" + allow.toString(), true);
        }
        model.addAttribute("outOrderNo", order.getOutOrderNo());
        model.addAttribute("body", order.getBody());
        model.addAttribute("amount", order.getAmount());
        model.addAttribute("orderId", order.getId());
        view = "pay";
        return view;
    }


    @ResponseString
    @PostMapping("/pay")
    @ApiOperation("收银台接口")
    public RespBody pay(Pay pay) {
        RespBody respBody = new RespBody();
        Order order = orderService.findById(pay.getOrderId());
        if (ObjectUtils.isEmpty(order)) {
            respBody.setRespInfo("订单不存在");
            return respBody;
        } else if (StatusDict.WAIT_PAY.equals(order.getStatus())) {
            // 二维码已生成，待支付
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            respBody.setBody(order.getCode());
            return respBody;
        } else if (!StatusDict.NORMAL.equals(order.getStatus())) {
            respBody.setRespInfo("订单已支付");
            return respBody;
        }
        order.setPayType(pay.getPayType());

        // 选择商户
        Business business = null;
        while (ObjectUtils.isEmpty(business)) {
            try {
                business = businessService.chooseBusiness(order, true);
            } catch (RuntimeException e) {
                respBody.setRespInfo("支付渠道异常，请联系管理员");
                String message = e.getMessage();
                switch (message) {
                    case "1":
                        logger.info("没有可用商户");
                        break;
                    case "0":
                        logger.info("仅支持循环");
                        break;
                    case "2":
                        logger.info("商户获取失败");
                        break;
                }
                return respBody;
            }
        }

        // 选中商户
        if (!ObjectUtils.isEmpty(business)) {
            order.setBusinessId(business.getId());
            Channel channel = channelService.findChannelByBusinessId(business.getId());
            switch (channel.getCode()) {
                case "shq": // 生活圈
                    shq(business, order, respBody);
                    break;
                case "shwx":// SH微信
                    shwx(business, order, respBody);
                    break;
                case "yiai"://财付通
                    yiai(business, order, respBody);
                    break;
                case "xjwg"://网关
                    xjwf(business, order, respBody, pay.getBankCode());
                    break;
                case "xjsm"://扫码
                    xjsmwf(business, order, respBody);
                    break;
                case "xjkj"://快捷
                    xjkjwf(business, order, respBody);
                    break;
//                case "zfbpcsm"://支付宝PC扫码
//                    zfbpcsm(business,order,respBody);
//                    break;
//                case "wxpcsm"://微信PC扫码
//                    wxpcsm(business,order,respBody);
//                    break;
                case "syksm": // 商云客扫码
                    syksm(business, order, respBody);
                    break;
                case "smzf1":
                    smzf1(business, order, respBody);
                    break;
//                case "ghtsm":
//                    ghtsm(business, order, respBody);
//                    break;
//                case "easyPay":
//                    easyPay(business, order, respBody);
//                    break;
                case "uline":
                    uline(business, order, respBody);
                    break;
                case "wjxjksm":
                    wjxjksm(business, order, respBody);
                    break;
//                case "yiaiwxh5":
//                    yiaiwxh5(business,order,respBody);
                case "selfZFB":
                    selfZFB(business, order, respBody);
                    break;
                case "selfZFB2":
                    selfZFB2(business, order, respBody);
                    break;
                case "QD":
                    QD(business, order, respBody);
                    break;
                case "YZ":
                    YZ(business, order, respBody);
                    break;
                case "DB":
                    DB(business, order, respBody);
                    break;
//                case "AKJSAPI":
//                    AKJSAPI(business, order, respBody);
//                    break;
                case "xmkzry":
                    xmkzry(business, order, respBody);
                    break;
                case "ryf":
                    ryf(business, order, respBody);
                    break;
                case "zpay":
                    zpay(business, order, respBody);
                    break;
                case "pay01":
                    pay01(business, order, respBody);
                    break;
                case "ns":
                    ns(business, order, respBody);
                    break;
                case "pay02":
                    pay02(business, order, respBody);
                    break;
                case "pay03":
                    pay03(business, order, respBody);
                    break;
                case "HYMT":
                    HYMT(business, order, respBody);
                    break;
                case "HJ":
                    HJ(business, order, respBody);
                    break;
                case "QFQ": // 七分钱
                    QFQ(business, order, respBody);
                    break;
                case "YLEWM":
                    YLEWM(business, order, respBody);
                    break;
                case "YLSM"://银联扫码
                    YLSM(business, order, respBody);
                    break;
                case "QFQSM":
                    QFQSM(business, order, respBody);
                    break;
                case "JDF":
                    jdf(business,order,respBody);
                    break;
                case "YL": //亿龙
                    YL(business,order,respBody);
                    break;
                case "SHYQ"://上海懿权
                    shyq(business,order,respBody);
                    break;
                default:
                    throw new BaseException("没有可用渠道 " + channel.getCode());
            }
        }

        return respBody;
    }

    private void shyq(Business business, Order order, RespBody respBody) {
        HashMap<String, String> params = new HashMap<>();
        params.put("version", "1.1");
        params.put("merchantId", business.getAccount());
        params.put("merchantTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        params.put("traceNO", order.getOrderNo());
        params.put("requestAmount", order.getRealAmount().toString()); // 3元
        params.put("returnUrl", "http://www.baidu.com");
        params.put("notifyUrl", HOST+"/notify/shyqNotify");
        params.put("goodsName", "商品");
        params.put("goodsCount", "1");
        params.put("ip", "192.168.0.1");
        params.put("paymentCount", "1");
        params.put("payment_1", "3_"+order.getRealAmount().toString()); //支付类型_支付金额
        System.out.println("开始签名》》》》》》》》》》》》》》》》》》》》");
        String sign = PayUtils.sign(params, business.getSecretKey());
        params.put("sign", sign);
        System.out.println("发送请求》》》》》》》》》》》》》》》》》》》》");
        String response = PayUtils.makeRequest(params,"http://119.28.34.43/mctrpc/order/mkReceiptOrder.htm");
        System.out.println(response);
        System.out.println("验证签名》》》》》》》》》》》》》》》》》》》》");
        boolean b = PayUtils.checkSign(response, business.getSecretKey());
        int begin = response.indexOf("{\"");
        int end = response.indexOf("\"}|");
        response = response.substring(begin,end)+"\"}";
        System.out.println(response);
        JSONObject jb = JSON.parseObject(response);
        if (b){
            System.out.println(jb);
            System.out.println(jb.getString("payments"));
            JSONArray ja = jb.getJSONArray("payments");
            String code = ja.getJSONObject(0).getJSONObject("itemResponseMsg").getString("barcodeInfo");
            if ("9".equals(jb.getString("orderStatus"))){
                order.setStatus(StatusDict.WAIT_PAY);
                respBody.setBody(code);
                respBody.setRespCode("1");
                respBody.setRespInfo("成功");
                order.setCode(code);
                orderService.save(order);
                return;
            }
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(jb.getString("errorMsg"));
        payFailed.setContent(jb.getString("errorMsg"));
        payFailed.setParams(jb.toJSONString());
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
        return;
    }

    private void YL(Business business, Order order, RespBody respBody) {
        System.out.println("===========");
        Map<String, String> requestBody = new HashMap<>();
        //PayTypeDict.ALI_CODE.equals(order.getPayType());
        PayTypeDict.ALI_WAP.equals(order.getPayType());
        requestBody.put("out_trade_no",order.getOrderNo());//商户单号
        if  (order.getRealAmount().doubleValue() <= 1000){
            requestBody.put("goods_name", "印度老山檀木手串");//商品名称
        }else {
            requestBody.put("goods_name", "黑檀木雕公鸡摆件");//商品名称
        }
        requestBody.put("total_amount", order.getRealAmount().toString());//交易金额(单位:元)
        requestBody.put("channel_code", "aliscpay");//支付渠道
        requestBody.put("device", "1");//支付设配 0.手机 1.电脑
        requestBody.put("notify_url", HOST+"/notify/YLNotify");//回调地址
        requestBody.put("remarks", "create_pay_order_test");//交易备注
        requestBody.put("appid", business.getAccount());//商户编码对应appid
        requestBody.put("request_time", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        requestBody.put("version", "1.0.0");
        String sign = ApiUtils.getSign(requestBody,business.getSecretKey());
        requestBody.put("sign",sign);
        Map<String,String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");
        System.out.println(HttpUtils.formatData(requestBody));
        HttpPost httpPost = new HttpPost("http://npay.elongpay.com/trade/create");
        StringEntity stringEntity = new StringEntity(JsonUtils.toJson(requestBody),DEFAULT_ENCODING);
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
        String res = null;
        try {
            res = HttpClientUtils.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(res);//请求返回结果
        JSONObject jb = JSON.parseObject(res);
        if ("0".equals(jb.getString("code"))){
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(jb.getString("content"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(jb.getString("content"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(jb.getString("code"));
        payFailed.setContent(jb.getString("biz_message"));
        payFailed.setParams(jb.toJSONString());
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
        return;
    }

    private void jdf(Business business, Order order, RespBody respBody) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Map<String, String> map = new TreeMap();
        if (PayTypeDict.QQ_WAP.equals(order.getPayType())){
            map.put("service", "pay.qq.wap");
        }else if(PayTypeDict.CODE_BANK.equals(order.getPayType())){
            map.put("service", "pay.unionpay.qrcode");
        }else if(PayTypeDict.QUICK_BANK.equals(order.getPayType())){
            map.put("service", "pay.b2c.wap");
        }else if(PayTypeDict.WX_CODE.equals(order.getPayType())){
            map.put("service", "pay.weixin.qrcode");
        }else if(PayTypeDict.WX_H5.equals(order.getPayType())){
            map.put("service", "pay.weixin.wap");
        }else if(PayTypeDict.ALI_CODE.equals(order.getPayType())){
            map.put("service", "pay.alipay.qrcode");
        }else if(PayTypeDict.ALI_WAP.equals(order.getPayType())){
            map.put("service", "pay.alipay.wap");
        }
        map.put("version", "1.0");
        map.put("merchantId", business.getAccount());
        map.put("orderNo", order.getOrderNo());
        map.put("tradeDate", sdf.format(date));
        map.put("tradeTime", "123015");
        String amount =  String.valueOf((int)(order.getRealAmount().multiply(new BigDecimal(100)).doubleValue()));
        map.put("amount", amount);
        map.put("clientIp", "127.0.0.1");
        map.put("notifyUrl", HOST+"/notify/jdfNotify");
        map.put("sign", com.qian.ddj.pay.util.SignUtils.createSign(map, business.getSecretKey()));
        String reqUrl = "https://paygw.pk10000.com/gateway";
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            List<NameValuePair> nvps = new ArrayList();
            for (String k : map.keySet()) {
                nvps.add(new BasicNameValuePair(k, map.get(k)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            httpPost.addHeader("Connection", "close");
            client = HttpClient.createHttpClient();
            response = client.execute(httpPost);
            System.out.println("==========");
            System.out.println(response);
            if (response != null && response.getEntity() != null) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                Map<String, String> resultMap = com.qian.ddj.pay.util.SignUtils.parseQuery(content);
                System.out.println(resultMap);
                if("0001".equals(resultMap.get("repCode"))){
                    order.setStatus(StatusDict.WAIT_PAY);
                    if (PayTypeDict.ALI_WAP != order.getPayType() && PayTypeDict.WX_H5 != order.getPayType()){
                        String retUrl = resultMap.get("resultUrl");
                        System.out.println(retUrl);
                        Document document =Jsoup.connect(retUrl).get();
                        document.html();
                        String html = document.html();
                        System.out.println(html);
                        Integer begin = html.indexOf("['script','[\"showQr(\\'");
                        Integer end = html.indexOf("\\')\"]']);");
                        System.out.println(begin+"      "+end);
                        html = html.substring(begin,end);
                        System.out.println("截取的字符串：\n"+html);
                        begin = html.indexOf("http");

                        html = html.substring(begin);
                        System.out.println("未转化的URL：\n"+html);
                        html = html.replaceAll("\\\\","");
                        respBody.setBody(html);
                        respBody.setRespCode("1");
                        respBody.setRespInfo("成功");
                        order.setCode(html);
                        orderService.save(order);
                        return;
                    }else {
                        respBody.setBody(resultMap.get("resultUrl"));
                        respBody.setRespCode("1");
                        respBody.setRespInfo("成功");
                        order.setCode(resultMap.get("resultUrl"));
                        orderService.save(order);
                        return;
                    }

                }
                PayFailed payFailed = new PayFailed();
                payFailed.setUserId(order.getUserId());
                payFailed.setOutOrderNo(order.getOutOrderNo());
                payFailed.setReason(resultMap.get("repMsg"));
                payFailed.setContent("数据签名验证错误");
                payFailed.setParams(resultMap.toString());
                payFaildService.simpleSave(payFailed);
                respBody.setRespInfo("失败");
                return;

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void QFQSM(Business business, Order order, RespBody respBody) {

    }

    private void YLSM(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 32) {
            orderNo = orderNo.substring(orderNo.length() - 29, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }
        System.out.println("下单。。。。。。。。。。。。。。");
        String pid = business.getBackup1();//机构号
        String gateWay = "http://120.77.22.14:8380/pay/gateway/unify.do";//请求
        SortedMap<String, String> requestMap = new TreeMap<String, String>();
        requestMap.put("TRDE_CODE", "20001");//交易码
        requestMap.put("PRT_CODE", pid);//机构号
        requestMap.put("VER_NO", "1.0");//版本号  1.0
        requestMap.put("MERC_ID", business.getAccount());//进件成功后返回的商户号
        requestMap.put("BIZ_CODE", "3007");//微信1003 支付宝2003QQ扫码5003 3003网银
        requestMap.put("ORDER_NO", orderNo);//订单号  确保接入系统唯一
        requestMap.put("TXN_AMT", String.valueOf(order.getRealAmount().doubleValue()));//订单金额
        requestMap.put("PRO_DESC", "");//商品描述

        requestMap.put("CARD_NO", "");//网银支付用
        requestMap.put("BNK_CD", "");//网银支付用  银行编码
        requestMap.put("ACC_TYP", "");//网银支付用  借贷标记

        requestMap.put("NOTIFY_URL", HOST+"/notify/YLSMNotify");//异步通知地址
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");// 生成随机字符串
        requestMap.put("NON_STR", nonce_str);//随机字符串
        requestMap.put("TM_SMP", System.currentTimeMillis()+"");//时间戳
        requestMap.put("SIGN_TYP", "MD5");//签名方式
        String sign = MD5Utils.getSign(requestMap, business.getSecretKey());
        System.out.println("数据签名成功 sign=" + sign);
        requestMap.put("SIGN_DAT", sign);//签名数据

        String json = JSON.toJSONString(requestMap);
        String ret = "";
        try {
            ret = HttpRequestUtil.httpPostSendReceive(gateWay, json);
        } catch (IOException e) {
            e.printStackTrace();
            respBody.setRespInfo("失败");
            return;
        }
        JSONObject jsonobj = JSON.parseObject(ret);
        String status = (String) jsonobj.get("RETURNCODE");
        String message = (String) jsonobj.get("RETURNCON");

        if (!status.equalsIgnoreCase("0000")) {
            System.out.println("失败描述："+message);
            PayFailed payFailed = new PayFailed();
            payFailed.setUserId(order.getUserId());
            payFailed.setOutOrderNo(order.getOutOrderNo());
            payFailed.setReason(status);
            payFailed.setContent(message);
            payFailed.setParams(ret);
            payFaildService.simpleSave(payFailed);
            respBody.setRespInfo("失败");
            return;
        }
        System.out.println("数据签名验证");
        if (!MD5Utils.checkSign(jsonobj, business.getSecretKey())) {
            System.out.println("数据签名验证错误");
            PayFailed payFailed = new PayFailed();
            payFailed.setUserId(order.getUserId());
            payFailed.setOutOrderNo(order.getOutOrderNo());
            payFailed.setReason(status);
            payFailed.setContent("数据签名验证错误");
            payFailed.setParams(ret);
            payFaildService.simpleSave(payFailed);
            respBody.setRespInfo("失败");
            return;
        }
        System.out.println("数据签名验证成功");
        String qrCode = (String) jsonobj.get("QR_CODE");
        String mch_id = (String) jsonobj.get("MERC_ID");
        String prt_code = (String) jsonobj.get("PRT_CODE");
        String out_trade_no = (String) jsonobj.get("OUT_TRADE_NO");
        System.out.println("返回url："+qrCode);
        System.out.println("返回外部订单号："+out_trade_no);
        System.out.println("返回商户号："+mch_id);
        System.out.println("返回机构号："+prt_code);
        order.setStatus(StatusDict.WAIT_PAY);
        respBody.setBody(qrCode);
        respBody.setRespCode("1");
        respBody.setRespInfo("成功");
        order.setCode(qrCode);
        orderService.save(order);

    }

    private void YLEWM(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 32) {
            orderNo = orderNo.substring(orderNo.length() - 29, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }
        Map<String, String> map = new HashMap<String, String>();
        String orderDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        map.put("amount", String.valueOf(order.getRealAmount().doubleValue()));
        map.put("notifyUrl", HOST+"/notify/YLEWMNotify");
        map.put("merchantNo", "B103973215");
        map.put("goodsName","一条裤子");
        map.put("orderIp","192.168.0.115");
        map.put("encrypt","T0");
        map.put("userid", business.getAccount());
        /** 参与验签的字段 */
        String sign = SignUtils.getSignParam(map);
        System.out.println("计算签名的报文为：" + sign);
        sign = SignUtils.getKeyedDigest(sign,business.getSecretKey());
        /** 上送的值为 */
        map.put("sign", sign);
        map.put("pay_number", orderNo);
        map.put("orderCode", "wlb_scanPay");
        String baowen = SignUtils.getSignParam(map);
        System.out.println("上送的报文为：" + map);
        String sr = HttpUtils.post("http://extman.kefupay.cn/pay/pay_mobile.action",baowen);
        System.out.println(sr);
        JSONObject jb = JSON.parseObject(sr);
        if ("1000".equals(jb.getString("respCode"))){
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(jb.getString("qrCode"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(jb.getString("qrCode"));
            order.setUpOrderNo(String.valueOf(jb.getString("orderId")));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(jb.getString("respInfo"));
        payFailed.setContent(sr);
        payFailed.setParams(sr);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    private void QFQ(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 30) {
            orderNo = orderNo.substring(orderNo.length() - 27, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Map<String, String> map = new TreeMap<>();
        map.put("service", "h5_t.gateway.pay");
//        map.put("channel", "alipay");
        if (order.getPayType().equals(PayTypeDict.WX_H5)){
            map.put("channel", "wx");
        }else {
            map.put("channel", "alipay");
        }
        map.put("inputCharset", "UTF-8");
        String frontUrl = order.getFrontUrl();
        if (StringUtils.isEmpty(frontUrl)) {
            frontUrl = HOST;
        }
        map.put("pgUrl", frontUrl);
        map.put("bgUrl", HOST + "/notify/QFQNotify");
        map.put("version", "v2.0");
        map.put("pageLanguage", "1");
        map.put("mchId", business.getAccount());
        map.put("mchOrderId", orderNo);
        map.put("orderAmt", String.valueOf(order.getRealAmount().doubleValue()));
        map.put("orderTimestamp", format.format(new Date()));
        map.put("prodName", System.currentTimeMillis() + "");
        map.put("prodDesc", System.currentTimeMillis() + "");
        map.put("payType", "1");
        map.put("orderTimeOut", "1800");
        try {
            String sign = com.qian.ddj.pay.util.RSAUtils.sign(SignUtils.params(map).getBytes(), null);
            map.put("signMsg", sign);
            map.put("signType", "RSA");
        } catch (Exception e) {
            e.printStackTrace();
        }
//        String receive = HttpUtils.post("http://zt.qifenmall.com/gateway.do", HttpUtils.formatData(map));
        String receive = HttpUtils.post("https://combinedpay.qifenqian.com/gateway.do", HttpUtils.formatData(map));
        System.out.println(receive);
        JSONObject resultMap = JSON.parseObject(receive);
        if ("SUCCESS".equals(resultMap.getString("returnCode"))) {
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(resultMap.getString("payUrl"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(resultMap.getString("payUrl"));
            order.setUpOrderNo(String.valueOf(resultMap.get("inOrderId")));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason((String) resultMap.get("returnMsg"));
        payFailed.setContent(receive);
        payFailed.setParams(receive);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    private void HJ(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 32) {
            orderNo = orderNo.substring(orderNo.length() - 29, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }

        Map<String, String> params = new TreeMap<>();
        params.put("amount", order.getRealAmount().toString());
        params.put("notifyUrl", HOST + "/notify/HJNotify");
        params.put("body", "test");
        params.put("mch_id", business.getBackup1());
        params.put("mch_key", business.getBackup2());
        params.put("userid", business.getAccount());
        /** 参与验签的字段 */
        String sign = SignUtils.sign(params, business.getSecretKey());
        /** 上送的值为 */
        params.put("sign", sign);
        params.put("orderCode", "hx_scanPay");
        params.put("pay_number", order.getOrderNo());
        String baowen = HttpUtils.formatData(params);
        String receive = HttpUtils.post("http://extman.kefupay.cn/pay/pay_mobile.action", baowen);
        log.info(receive);
        JSONObject data = JSON.parseObject(receive);
        if ("0".equalsIgnoreCase(data.getString("respCode")) && "SUCCESS".equalsIgnoreCase(data.getString("respInfo"))) {
            String qrcode = data.getString("code_url");
//            qrcode = toShort(qrcode);
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(qrcode);
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(qrcode);
            order.setUpOrderNo(data.getString("orderId"));
            orderService.save(order);
            return;
        }

        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(data.getString("respInfo"));
        payFailed.setContent(receive);
        payFailed.setParams(baowen);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    private void HYMT(Business business, Order order, RespBody respBody) {
        Map<String, String> map = new TreeMap<>();
        map.put("amount", order.getRealAmount().toString());
        map.put("appid", business.getAccount());
        map.put("subject", "支付");
        map.put("orderid", order.getOrderNo());
        map.put("payType", "23");
        map.put("notifyUrl", HOST + "/notify/HYMTNotify");
        map.put("returnUrl", order.getFrontUrl());
        map.put("orderInfo", "支付");
        map.put("signature", SignUtils.sign(map, business.getSecretKey()));

        String body = JSON.toJSONString(map);
        String receive = HttpUtils.post("http://p.51paypay.net/api/v1/pay/submit", body);
        System.out.println(receive);
        JSONObject jsonObject = JSON.parseObject(receive);
        JSONObject data = jsonObject.getJSONObject("data");
        if (data.getIntValue("status") == 0) {
            String qrcode = data.getString("pay_url");
//            qrcode = toShort(qrcode);
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(qrcode);
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(qrcode);
            orderService.save(order);
            return;
        }

        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(data.getString("error"));
        payFailed.setContent(receive);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }


    private void pay03(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 32) {
            orderNo = orderNo.substring(orderNo.length() - 29, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }
        Map<String, String> requestMap = new TreeMap<String, String>();
        requestMap.put("TRDE_CODE", "20001");//交易码
        requestMap.put("PRT_CODE", business.getAccount());//机构号
        requestMap.put("VER_NO", "1.0");//版本号  1.0
        requestMap.put("MERC_ID", business.getBackup1());//进件成功后返回的商户号
        if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
            requestMap.put("BIZ_CODE", "1003");//微信1003 支付宝2003QQ扫码5003
        } else if (order.getPayType().equals(PayTypeDict.ALI_CODE) || order.getPayType().equals(PayTypeDict.ALI_WAP)) {
            requestMap.put("BIZ_CODE", "2003");//微信1003 支付宝2003QQ扫码5003
        } else if (order.getPayType().equals(PayTypeDict.QQ) || order.getPayType().equals(PayTypeDict.QQ_WAP)) {
            requestMap.put("BIZ_CODE", "5003");//微信1003 支付宝2003QQ扫码5003
        } else {
            throw new BaseException("没有对应通道");
        }
        requestMap.put("ORDER_NO", order.getOrderNo());//订单号  确保接入系统唯一
        requestMap.put("TXN_AMT", order.getRealAmount().toString());//订单金额
        requestMap.put("PRO_DESC", "shop");//商品描述
        requestMap.put("NOTIFY_URL", HOST + "/notify/pay03Notify");//异步通知地址
        String nonce_str = System.currentTimeMillis() + "";// 生成随机字符串
        requestMap.put("NON_STR", nonce_str);//随机字符串
        requestMap.put("TM_SMP", nonce_str);//时间戳
        requestMap.put("SIGN_TYP", "MD5");//签名方式
        requestMap.put("SIGN_DAT", DigestUtils.md5Hex(SignUtils.params(requestMap) + "&KEY=" + business.getSecretKey()));
        String body = JSON.toJSONString(requestMap);
        log.info(body);
        String receive = HttpUtils.post("http://120.77.22.14:8380/pay/gateway/unify.do", body);
        log.info(receive);
        JSONObject data = JSON.parseObject(receive);
        if ("0000".equalsIgnoreCase(data.getString("RETURNCODE"))) {
            String qrcode = data.getString("QR_CODE");
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(qrcode);
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(qrcode);
            order.setUpOrderNo(data.getString("OUT_TRADE_NO"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(data.getString("RETURNCON"));
        payFailed.setContent(receive);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    private void pay02(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 20) {
            orderNo = orderNo.substring(orderNo.length() - 17, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> map = new TreeMap<>();
        map.put("pay_memberid", business.getAccount());
        map.put("pay_orderid", order.getOrderNo());
        map.put("pay_amount", order.getRealAmount().toString());
        map.put("pay_applydate", format.format(new Date()));
//        map.put("pay_applydate", "2017-12-19 10:43:49");
        if (PayTypeDict.WX_H5.equals(order.getPayType())) {
            map.put("pay_bankcode", "901");
        } else if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
            map.put("pay_bankcode", "902");
        } else if (PayTypeDict.ALI_CODE.equals(order.getPayType()) || PayTypeDict.ALI_WAP.equals(order.getPayType())) {
            map.put("pay_bankcode", "904");
        } else {
            throw new BaseException("未开通对应通道");
        }
        map.put("pay_notifyurl", HOST + "/notify/pay02Notify");
        map.put("pay_callbackurl", "http://www.baidu.com");
        map.put("pay_md5sign", SignUtils.sign(map, business.getSecretKey()).toUpperCase());
        map.put("pay_productname", orderNo);
        String body = SignUtils.params(map);
        log.info("请求数据" + body);
        String receive = null;
        if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
            receive = HttpUtils.post("http://u9pay.com/Pay_Index.html", body);
            Document document = Jsoup.parse(receive);
            Elements elementsByTag = document.getElementById("weixin").getElementsByTag("img");
            String qrcode = elementsByTag.get(1).attr("src");
            if (org.apache.commons.lang3.StringUtils.isNotBlank(qrcode)) {
                qrcode = "image||http://u9pay.com" + qrcode;
                order.setStatus(StatusDict.WAIT_PAY);
                respBody.setBody(qrcode);
                respBody.setRespCode("1");
                respBody.setRespInfo("成功");
                order.setCode(qrcode);
                orderService.save(order);
                return;
            }
        } else if (PayTypeDict.WX_H5.equals(order.getPayType()) || PayTypeDict.ALI_CODE.equals(order.getPayType()) || PayTypeDict.ALI_WAP.equals(order.getPayType())) {
            HttpURLConnection conn = null;
            try {
                URL _url = new URL("http://u9pay.com/Pay_Index.html");
                conn = (HttpURLConnection) _url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setConnectTimeout(50000);
                conn.setReadTimeout(50000);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
                conn.connect();
                OutputStream out = conn.getOutputStream();
                out.write(body.getBytes("UTF-8"));
                out.flush();
                out.close();
                receive = conn.getHeaderField("Location");
                if (org.apache.commons.lang3.StringUtils.isBlank(receive) && (!PayTypeDict.WX_H5.equals(order.getPayType()))) {
                    receive = conn.getURL().toString();
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(receive)) {
                        receive = receive.replaceFirst("http://a.bldpay.com:8209/payapi/wap/\\?url=", "");
                    }
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(receive)) {
                    order.setStatus(StatusDict.WAIT_PAY);
                    String longUrl = URLEncoder.encode(receive);
                    String shortUrl = HttpUtils.get("http://suo.im/api.php?url=" + longUrl);
                    respBody.setBody(shortUrl);
                    respBody.setRespCode("1");
                    respBody.setRespInfo("成功");
                    order.setCode(shortUrl);
                    orderService.save(order);
                    return;
                }
            } catch (Exception var9) {
                throw new RuntimeException(var9);
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        if (org.apache.commons.lang3.StringUtils.isBlank(receive)) {
            receive = HttpUtils.post("http://u9pay.com/Pay_Index.html", body);
        }
        JSONObject data = JSON.parseObject(receive);
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(data.getString("msg"));
        payFailed.setContent(receive);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    private void ns(Business business, Order order, RespBody respBody) {
        Map<String, String> map = new TreeMap();
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour >= 22 && hour <= 9) {
            map.put("route", "1");
        } else {
            map.put("route", "0");
        }
        map.put("body", order.getOutOrderNo());
        map.put("amount", order.getRealAmount().toString());
        map.put("nonce_str", System.currentTimeMillis() + "");
        map.put("notifyUrl", HOST + "/notify/nsNotify");
        map.put("userid", business.getAccount());

        map.put("sign", SignUtils.sign(map, business.getSecretKey()));
        map.put("orderCode", "ns_newWeChatPay");
        map.put("pay_number", order.getOrderNo());
        String baowen = HttpUtils.formatData(map);
        log.info("上送的报文为：" + baowen);
        String sr = HttpUtils.post("http://extman.kefupay.cn/pay/pay_mobile.action", baowen);
        log.info(sr);
        JSONObject data = JSON.parseObject(sr);
        if ("000000".equalsIgnoreCase(data.getString("respCode"))) {
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(data.getString("payUrl"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(data.getString("payUrl"));
            order.setUpOrderNo(data.getString("orderId"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(data.getString("respInfo"));
        payFailed.setContent(sr);
        payFailed.setParams(baowen);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    private void pay01(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 32) {
            orderNo = orderNo.substring(orderNo.length() - 29, orderNo.length());
             orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }

        Map<String, String> map = new TreeMap<>();
        map.put("merchNo", business.getAccount());
        map.put("orderNo", order.getOrderNo());
        map.put("transAmount", order.getRealAmount().multiply(new BigDecimal(100)).setScale(0).toString());
        map.put("productName", "productName");
        map.put("notifyUrl", "http://778vpn.com/notify/pay01Notify");
        map.put("sign", DigestUtils.md5Hex(SignUtils.params(map) + business.getSecretKey()));
        String body = JSON.toJSONString(map);
        log.info(body);
        String receive;
        if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
            receive = HttpUtils.post("http://47.94.208.216:8080/app/doWXPay.do", body);
        } else if (PayTypeDict.QQ.equals(order.getPayType()) || PayTypeDict.QQ_WAP.equals(order.getPayType())) {
            receive = HttpUtils.post("http://47.94.208.216:8080/app/doQQPay.do", body);
        } else {
            throw new BaseException("支付类型错误");
        }
        log.info(receive);

        JSONObject data = JSON.parseObject(receive);
        if ("00000".equalsIgnoreCase(data.getString("respCode"))) {
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(data.getString("qrcodeUrl"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(data.getString("qrcodeUrl"));
            order.setUpOrderNo(data.getString("orderId"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(data.getString("respDesc"));
        payFailed.setContent(receive);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    /**
     * zpay 2017-12-01 12:06:11
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void zpay(Business business, Order order, RespBody respBody) {
        Map<String, String> map = new TreeMap<>();
        map.put("partner_id", business.getAccount());
        map.put("app_id", business.getBackup1());
        if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
            map.put("wap_type", "4");
        } else if (order.getPayType().equals(PayTypeDict.QQ) || order.getPayType().equals(PayTypeDict.QQ_WAP)) {
            map.put("wap_type", "6");
        }
        map.put("money", order.getRealAmount().multiply(new BigDecimal(100)).setScale(0).toString());
        map.put("out_trade_no", order.getOrderNo());
        map.put("subject", URLEncoder.encode("游戏点卡"));
//        map.put("imei", "1");
//        map.put("qn", "1");
        String sign = SignUtils.sign(map, business.getSecretKey()).toUpperCase();
        map.put("sign", sign);
        map.put("subject", "游戏点卡");
        String body = HttpUtils.formatData(map);
        System.out.println(body);
        String code = null;
        String receive = null;
        try {
            receive = HttpUtils.get("http://pay.csl2016.cn:8000/createOrder.e", map);
            System.out.println(receive);
            if ("4".equalsIgnoreCase(map.get("wap_type"))) {
                code = Jsoup.parse(receive).getElementsByTag("img").attr("src");
            } else if ("6".equalsIgnoreCase(map.get("wap_type"))) {
                code = Jsoup.parse(receive).getElementsByTag("a").attr("href");
            }
            if (code.indexOf("https://api.ulopay.com/pay/qrcode?code=") != -1) {
                code = code.replaceFirst("https://api.ulopay.com/pay/qrcode\\?code=", "");
            } else {
                throw new BaseException();
            }
        } catch (Exception e) {
            e.printStackTrace();
            PayFailed payFailed = new PayFailed();
            payFailed.setUserId(order.getUserId());
            payFailed.setOutOrderNo(order.getOutOrderNo());
            payFailed.setReason("");
            payFailed.setContent(receive);
            payFailed.setParams(body);
            payFaildService.simpleSave(payFailed);
            respBody.setRespInfo("失败");
            return;
        }
        order.setStatus(StatusDict.WAIT_PAY);
        respBody.setBody(code);
        respBody.setRespCode("1");
        respBody.setRespInfo("成功");
        order.setCode(code);
        orderService.save(order);
        return;
    }

    /**
     * xmkzry 2017-11-28 13:39:54
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void xmkzry(Business business, Order order, RespBody respBody) {
        String secret = business.getSecretKey();
        Map<String, String> map = new TreeMap<>();//所有的业务参数放入这个map集合
        map.put("version", "1.0.1");
        map.put("orgOrderNo", order.getOrderNo());
        map.put("subject", "pay");
        map.put("amount", order.getRealAmount().toString());
        map.put("notifyUrl", HOST + "/notify/xmkzryNotify");//路径进行encoder编码
        map.put("tranTp", "0");
        if (order.getPayType().equals(PayTypeDict.ALI_CODE) || order.getPayType().equals(PayTypeDict.ALI_WAP)) {
            map.put("source", "ZFBZF");
        } else if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
            map.put("source", "WXZF");
        } else if (order.getPayType().equals(PayTypeDict.QQ) || order.getPayType().equals(PayTypeDict.QQ_WAP)) {
            map.put("source", "QQZF");
        }
        String param = SignUtils.params(map);//按照 abcd顺序排序 并转化为id=1&name=tom&age=23 的形式
        String base = Base64Utils.encodeToString(param.getBytes());
        String aesparam = AESUtil.encrypt(base, secret);
        Map<String, String> paramValues = new TreeMap<>();//所有请求参数
        paramValues.put("method", "scanPay"); //请求的方法名  必填 区分不同的请求
        paramValues.put("appKey", business.getAccount());//商户号 必填
        paramValues.put("v", "1.0");//版本 必填  暂定1.0
        paramValues.put("format", "Json");// 返回格式 暂时只支持json 必填
        paramValues.put("params", aesparam); // 所有参数转成的字符串  必填

        StringBuilder sb = new StringBuilder();
        sb.append(secret);
        for (String paramName : paramValues.keySet()) {
            sb.append(paramName).append(paramValues.get(paramName));
        }
        sb.append(secret);
        String sign = DigestUtils.sha1Hex(sb.toString()).toUpperCase(); //验签
        paramValues.put("sign", sign);//添加验签
        String body = HttpUtils.formatData(paramValues);
        System.out.println(body);
        String response = HttpUtils.post("http://testapi.xmkzry.com/router", body);//请求
        System.out.println(response);
        JSONObject result = JSON.parseObject(response);
        JSONObject data = result.getJSONObject("data");
        if ("200".equalsIgnoreCase(result.getString("errorCode"))) {
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(data.getString("qrCode"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(data.getString("qrCode"));
            order.setUpOrderNo(data.getString("tradeNo"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(data.getString("remark") + data.getString("message"));
        payFailed.setContent(response);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
        return;
    }

    /**
     * ryf 2017-11-28 14:47:22
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void ryf(Business business, Order order, RespBody respBody) {

        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 30) {
            orderNo = orderNo.substring(orderNo.length() - 27, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }

        Map<String, String> map = new TreeMap<>();
        map.put("amount", order.getRealAmount().toString());
        map.put("notifyUrl", HOST + "/notify/ryfNotify");
        if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
            map.put("payType", "2");
        } else if (order.getPayType().equals(PayTypeDict.QQ) || order.getPayType().equals(PayTypeDict.QQ_WAP)) {
            map.put("payType", "4");
        } else if (order.getPayType().equals(PayTypeDict.JD)) {
            map.put("payType", "1");
        }
        map.put("goodsName", "pay");
        map.put("settleType", "1");
        map.put("userid", business.getAccount());
        /** 参与验签的字段 */
        String sign = SignUtils.sign(map, business.getSecretKey());
        /** 上送的值为 */
        map.put("sign", sign);
        map.put("pay_number", order.getOrderNo());
        map.put("orderCode", "ryf_scanPay");
        String baowen = HttpUtils.formatData(map);
        log.info("上送的报文为：" + map);
        String sr = HttpUtils.post("http://extman.kefupay.cn/pay/pay_mobile.action", baowen);
        log.info(sr);
        JSONObject result = JSON.parseObject(sr);
        if ("00".equalsIgnoreCase(result.getString("respCode"))) {
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(result.getString("barCode"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");
            order.setCode(result.getString("barCode"));
            order.setUpOrderNo(result.getString("orderId"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(result.getString("respInfo"));
        payFailed.setContent(sr);
        payFailed.setParams(baowen);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
        return;
    }

    /**
     * AK 微信公众号 2017-11-27 11:03:55
     *
     * @param business
     * @param order
     * @param respBody
     */
//    private void AKJSAPI(Business business, Order order, RespBody respBody) {
//        log.info("invoke easyPay_JSAPI method....");
//        ApiClient apiClient = ApiClientFactory.newClient("https://gw.ak47pay.com/native/", "ZFCK24000JAXS", "2017102821494327000");
//        ApiRequestBuilder builder = ApiRequestBuilder.newInstance("com.opentech.cloud.easypay.trade.create", "0.0.1");
//        builder.addParameter("merchantNo", "ZFCK24000JAXS");
//        builder.addParameter("outTradeNo", order.getOrderNo());
//        builder.addParameter("amount", order.getRealAmount().multiply(new BigDecimal(100)).longValue());
//        if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
//            builder.addParameter("payType", "WECHAT_JSAPI_PAY");
//        }
//        builder.addParameter("content", "content");
//        builder.addParameter("callbackURL", HOST + "/notify/easyPayNotify");
//        ApiResponse response = apiClient.invoke(builder.build());
//        String res = JSON.toJSONString(response);
//        log.info(res);
//        if (response.isSucceed()) {
//            Map<String, String> map = response.getData(Map.class);
//            order.setStatus(StatusDict.WAIT_PAY);
//            respBody.setBody(map.get("paymentInfo"));
//            respBody.setRespCode("1");
//            respBody.setRespInfo("成功");
//            order.setCode(map.get("paymentInfo"));
//            order.setUpOrderNo(map.get("tradeNo"));
//            orderService.save(order);
//            return;
//        }
//        PayFailed payFailed = new PayFailed();
//        payFailed.setUserId(order.getUserId());
//        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(response.getMsg());
//        payFailed.setContent(res);
//        payFailed.setParams(JSON.toJSONString(builder.build().getParameters()));
//        payFaildService.simpleSave(payFailed);
//        respBody.setRespInfo("失败");
//        return;
//    }

    /**
     * 多宝  2017-11-25 22:54:29
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void DB(Business business, Order order, RespBody respBody) {

        Map<String, String> map = new LinkedHashMap<>();
        map.put("parter", business.getAccount());
        if (order.getPayType().equals(PayTypeDict.ALI_CODE) || order.getPayType().equals(PayTypeDict.ALI_WAP)) {
            map.put("type", "1003");
        } else if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
            map.put("type", "1004");
        } else if (order.getPayType().equals(PayTypeDict.QQ) || order.getPayType().equals(PayTypeDict.QQ_WAP)) {
            map.put("type", "1009");
        }
        map.put("value", order.getRealAmount().toString());
        map.put("orderid", order.getOrderNo());
        map.put("callbackurl", HOST + "/notify/DBNotify");
        String body = SignUtils.params(map);
        map.put("sign", DigestUtils.md5Hex(body + business.getSecretKey()));
        body = HttpUtils.formatData(map);
        log.info(body);
        String receive = HttpUtils.get("http://api.dbopay.com/bank/?" + body);

        String code = null;
        if (order.getPayType().equals(PayTypeDict.ALI_CODE) || order.getPayType().equals(PayTypeDict.ALI_WAP)) {
            Document document = Jsoup.parse(receive);
            Element image2 = document.getElementById("Image2");
            String src = image2.attr("src");
            code = src.replaceFirst("/MakeQRCode.aspx\\?data=", "");
            code = URLDecoder.decode(code);
        } else if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
            StringBuilder stringBuilder = new StringBuilder();
            Document document = Jsoup.parse(receive);

            Element form = document.getElementById("mobaopaysubmit");
            Elements children = form.children();
            for (Element element : children) {
                stringBuilder.append(element.attr("name"))
                        .append("=")
                        .append(element.val())
                        .append("&");
            }
            receive = HttpUtils.post(form.attr("action"), stringBuilder.toString());

            stringBuilder = new StringBuilder();
            document = Jsoup.parse(receive);
            form = document.getElementById("weChatPayForm");
            children = form.children();
            for (Element element : children) {
                stringBuilder.append(element.attr("name"))
                        .append("=")
                        .append(element.val())
                        .append("&");
            }
            receive = HttpUtils.post("http://pay.ysspay.cn/weChatPay", stringBuilder.toString());
            JSONObject jsonObject = JSON.parseObject(receive);
            code = jsonObject.getJSONArray("data").getString(1);
        } else if (order.getPayType().equals(PayTypeDict.QQ) || order.getPayType().equals(PayTypeDict.QQ_WAP)) {
            StringBuilder stringBuilder = new StringBuilder();
            Document document = Jsoup.parse(receive);
            Element form = document.getElementById("mobaopaysubmit");
            Elements children = form.children();
            for (Element element : children) {
                stringBuilder.append(element.attr("name"))
                        .append("=")
                        .append(element.val())
                        .append("&");
            }
            receive = HttpUtils.post(form.attr("action"), stringBuilder.toString());
            stringBuilder = new StringBuilder();
            document = Jsoup.parse(receive);
            form = document.getElementById("qqPayForm");
            children = form.children();
            for (Element element : children) {
                stringBuilder.append(element.attr("name"))
                        .append("=")
                        .append(element.val())
                        .append("&");
            }
            receive = HttpUtils.post("http://pay.ysspay.cn/qqPay", stringBuilder.toString());
            JSONObject jsonObject = JSON.parseObject(receive);
            code = jsonObject.getJSONArray("data").getString(1);
        }

        if (!StringUtils.isEmpty(code)) {
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(code);
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");

            order.setCode(code);
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason("");
        payFailed.setContent(receive);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");

    }

    /**
     * YZ 2017-11-23 17:03:58
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void YZ(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 18) {
            orderNo = orderNo.substring(orderNo.length() - 15, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }
        Map<String, String> map = new TreeMap<>();
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        map.put("mch_no", business.getAccount());
        map.put("merchantOutOrderNo", order.getOrderNo());
        map.put("noncestr", String.valueOf(Math.round(Math.random() * 100000)));
        map.put("notifyUrl", HOST + "/notify/yzNotify");
        map.put("orderMoney", order.getRealAmount().toString());
        map.put("orderTime", time);

        String sign = SignUtils.sign(map, business.getSecretKey());
        map.put("sign", sign);
        if (PayTypeDict.ALI_CODE.equals(order.getPayType()) || PayTypeDict.ALI_WAP.equals(order.getPayType())) {
            map.put("type", "1");
        } else if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
            map.put("type", "2");
        }
        map.put("method", "2");
        String body = HttpUtils.formatData(map);
        log.info(body);
        String receive = HttpUtils.post("http://jh.yizhibank.com/groupapi/createOrder", body);
        log.info(receive);

        JSONObject result = JSON.parseObject(receive);
        if (StringUtils.isEmpty(result.getString("code"))) {
            order.setStatus(StatusDict.WAIT_PAY);
            String code = result.getString("url");
            respBody.setBody(code);
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");

            order.setCode(code);
            order.setUpOrderNo(result.getString("yft1403201711210199"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(result.getString("msg"));
        payFailed.setContent(receive);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    /**
     * 渠道 2017-11-23 11:43:13
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void QD(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 30) {
            orderNo = orderNo.substring(orderNo.length() - 27, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }

        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);

        Map<String, String> map = new TreeMap<>();
        map.put("orgno", business.getAccount());
        map.put("secondtimestamp", timeStamp);
        map.put("nonce_str", timeStamp);
        map.put("body", timeStamp);
        map.put("total_fee", order.getRealAmount().toString());
        map.put("t0t1", "T1");
        if (PayTypeDict.ALI_CODE.equals(order.getPayType()) || PayTypeDict.ALI_WAP.equals(order.getPayType())) {
            map.put("channel", "alipay");
        } else if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
            map.put("channel", "wechat");
        }
        map.put("trade_type", "NATIVE");
        map.put("out_trade_no", order.getOrderNo());
        map.put("sign", SignUtils.sign(map, business.getSecretKey()).toUpperCase());
        String body = HttpUtils.formatData(map);
        log.info(body);
        String receive = HttpUtils.post(business.getBackup1(), body);
        log.info(receive);
        JSONObject result = JSON.parseObject(receive);
        if ("900".equals(result.getString("status"))) {
            JSONObject data = result.getJSONObject("data");
            order.setStatus(StatusDict.WAIT_PAY);
            String code = data.getString("code_url");
            respBody.setBody(code);
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");

            order.setCode(code);
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(result.getString("info"));
        payFailed.setContent(receive);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    private boolean verifyOrder(PlaceOrder placeOrder, User user, Model model) {
        // 验证商户
        if (ObjectUtils.isEmpty(user)) {
            model.addAttribute("error", "商户不存在");
            return false;
        }

        if (user.getStatus().equals(StatusDict.CLOSE)) {
            model.addAttribute("error", "商户已停用");
            return false;
        }
        // 验证签名
        boolean verifySign = false;
        try {
            Map map = placeOrder.getMap();
            String sign = (String) map.get("sign");
            sign = sign.replaceAll("%2B","\\+");
            map.remove("sign");
            byte[] data = SignUtils.params(map).getBytes("utf-8");
           verifySign = RSASignUtils.verify(data,user.getPublicKey(),sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!verifySign) {
            model.addAttribute("error", "签名错误");
            return false;
        }

        // 判断订单是否存在
        Order order = new Order();
        order.setOutOrderNo(placeOrder.getOutOrderNo());
        order.setUserId(user.getId());

        Order order1 = orderService.findOne(order);
        if (!ObjectUtils.isEmpty(order1)) {
            model.addAttribute("error", "订单号重复");
            return false;
        }

        return true;
    }


    /**
     * 优畅
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void uline(Business business, Order order, RespBody respBody) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 32) {
            orderNo = orderNo.substring(orderNo.length() - 29, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                respBody.setRespInfo("下单失败，请重新下单");
                return;
            }
        }
        SortedMap<String, String> map = new TreeMap<>();
        map.put("out_trade_no", order.getOrderNo());
        map.put("total_fee", order.getRealAmount().multiply(new BigDecimal(100)).setScale(0).toString());
        map.put("spbill_create_ip", "127.0.0.1");
        map.put("mch_id", business.getAccount());
        map.put("body", "body");
        map.put("notify_url", HOST + "/notify/ulineNotify");
        if (order.getPayType().equals(PayTypeDict.WX_CODE))
            map.put("trade_type", "NATIVE");
        map.put("nonce_str", String.valueOf(System.currentTimeMillis()));

        String sign = SignUtils.sign(map, business.getSecretKey()).toUpperCase();
        map.put("sign", sign);

        String reqUrl;
        if (order.getPayType().equals(PayTypeDict.WX_CODE))
            reqUrl = "http://api.cmbxm.mbcloud.com/wechat/orders";
        else
            reqUrl = "http://api.cmbxm.mbcloud.com/alipay/orders/precreate";
        String body = XmlUtils.parseXML(map);
        log.info("reqParams:" + body);
        String res = HttpUtils.post(reqUrl, body);
        log.info(res);
        Map<String, String> resultMap = null;
        try {
            resultMap = XmlUtils.toMap(res.getBytes(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("SUCCESS".equals(resultMap.get("return_code")) && "SUCCESS".equals(resultMap.get("result_code"))) {
            order.setStatus(StatusDict.WAIT_PAY);
            String code;
            if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
                code = resultMap.get("code_url");
            } else {
                code = resultMap.get("qr_code");
            }
            respBody.setBody(code);
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");

            order.setCode(code);
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(resultMap.get("return_msg").toString());
        payFailed.setContent(res);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");

    }

    /**
     * 商云客 预下单接口(二维码支付(扫码支付))
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void syksm(Business business, Order order, RespBody respBody) {
        Map<String, String> map = new LinkedHashMap<>();

        map.put("p0_Cmd", "PreCreate");
        map.put("p1_Account", business.getAccount());
        map.put("p2_Amt", order.getRealAmount().toString());
        map.put("p3_ProductCode", "QR_CODE_OFFLINE");
        if (order.getPayType().equals(PayTypeDict.ALI_CODE) || order.getPayType().equals(PayTypeDict.ALI_WAP))
            map.put("p7_plat", "5");
        else if (order.getPayType().equals(PayTypeDict.WX_CODE))
            map.put("p7_plat", "6");
        else {
            respBody.setRespInfo("支付方式不正确");
            return;
        }
        map.put("p8_Channel", "1");
        map.put("p9_Notify_Url", HOST + "/notify/syksmNotify");

        String sign = SignUtils.params(map);
        sign = DigestUtils.md5Hex(sign + "&key=D81243076DDAD150A1034725E56511F8");
        map.put("hmac", sign);
        String body = SignUtils.params(map);
        String rec = HttpUtils.post("http://a.xfpay.cn/api/ApiHandler.ashx", body);
        log.info(rec);
        JSONObject result = JSON.parseObject(rec);
        String data = result.getString("data");
        Map<String, String> dataMap = JSON.parseObject(data, Map.class);
        if ("100".equals(result.get("result"))) {
            order.setUpOrderNo(dataMap.get("out_trade_no"));
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(dataMap.get("qr_code"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");

            order.setCode(dataMap.get("qr_code"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(dataMap.get("detail_error_des").toString());
        payFailed.setContent(rec);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
    }

    /**
     * SH微信支付
     *
     * @param business
     * @param order
     * @param respBody
     */
    private void shwx(Business business, Order order, RespBody respBody) {
        Map<String, String> map = new TreeMap<>();
        String orderDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        map.put("subMchId", business.getAccount());
        map.put("orderDate", orderDate);
        map.put("body", "商品");
        map.put("amount", order.getRealAmount().toString());
        map.put("productId", "商品名称");
        map.put("notifyUrl", HOST + "/notify/shwxNotify");
        map.put("userid", business.getBackup1());
        /** 参与验签的字段 */
        String sign = SignUtils.params(map);
        sign = DigestUtils.md5Hex(sign + business.getSecretKey());
        /** 上送的值为 */
        map.put("sign", sign);
        map.put("pay_number", order.getOrderNo());
        map.put("orderCode", "kl_WXPay");
        String baowen = SignUtils.params(map);
        log.info("上送的报文为：" + baowen);
        String sr = HttpUtils.post("http://extman.kefupay.cn/newWechats/newWeChatpayment_mobile.action", baowen);
        log.info(sr);
        Map<String, String> result = JSON.parseObject(sr, Map.class);
        if ("000000".equals(result.get("respCode"))) {
            order.setUpOrderNo(result.get("orderId"));
            order.setStatus(StatusDict.WAIT_PAY);
            respBody.setBody(result.get("codeUrl"));
            respBody.setRespCode("1");
            respBody.setRespInfo("成功");

            order.setCode(result.get("codeUrl"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(result.get("respInfo").toString());
        payFailed.setContent(sr);
        payFailed.setParams(JSONObject.toJSONString(result));
        payFaildService.simpleSave(payFailed);
        respBody.setRespInfo("失败");
        return;
    }

    /**
     * 生活圈支付
     *
     * @param business
     * @param order
     */
    private void shq(Business business, Order order, RespBody model) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 32) {
            orderNo = orderNo.substring(orderNo.length() - 29, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                model.setRespInfo("下单失败，请重新下单");
                return;
            }
        }

        Map<String, String> map = new TreeMap<>();
        map.put("app_id", business.getAccount());
        map.put("method", "openapi.payment.order.scan");
        map.put("format", "json");
        map.put("sign_method", "md5");
        map.put("nonce", String.valueOf(System.currentTimeMillis()));
        map.put("version", "1.0");
        Map<String, String> content = new HashMap<>();
        content.put("merchant_order_sn", order.getOrderNo());
        if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
            content.put("type", "1");
        } else if (order.getPayType().equals(PayTypeDict.ALI_CODE) || order.getPayType().equals(PayTypeDict.ALI_WAP)) {
            content.put("type", "2");
        }
        content.put("total_fee", order.getRealAmount().toString());
        content.put("store_id", business.getBackup1());
        content.put("call_back_url", HOST + "/notify/shqNotify");
        map.put("biz_content", JSON.toJSONString(content));
        String sign = DigestUtils.md5Hex(SignUtils.params(map) + business.getSecretKey()).toUpperCase();
        map.put("sign", sign);
        String body = JSON.toJSONString(map);
        logger.info("BODY = " + body);
        String receive = HttpUtils.post("https://shq-api.51fubei.com/gateway", body);
        logger.info("receive = " + receive);
        Map<String, Object> result = JSON.parseObject(receive, Map.class);
        if ("200".equals(result.get("result_code").toString())) {
            Map<String, String> data = JSON.parseObject(result.get("data").toString(), Map.class);
            order.setUpOrderNo(data.get("order_sn"));
            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(data.get("qr_code"));
            model.setRespCode("1");
            model.setRespInfo("成功");

            order.setCode(data.get("qr_code"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(result.get("respInfo").toString());
        payFailed.setContent(receive);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }

    public void yiai(Business business, Order order, RespBody model) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 30) {
            orderNo = orderNo.substring(orderNo.length() - 27, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                model.setRespInfo("下单失败，请重新下单");
                return;
            }
        }

        Map<String, String> map = new LinkedHashMap<>();
        map.put("parter", business.getAccount());
        if (PayTypeDict.QQ.equals(order.getPayType()) || PayTypeDict.QQ_WAP.equals(order.getPayType())) {
            map.put("type", "993");
        } else if (PayTypeDict.ALI_CODE.equals(order.getPayType()) || PayTypeDict.ALI_WAP.equals(order.getPayType())) {
            map.put("type", "992");
        } else if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
            map.put("type", "1004");
        } else if (PayTypeDict.WX_H5.equals(order.getPayType())) {
            map.put("type", "1006");
        }
        map.put("value", order.getRealAmount().toString());
        map.put("orderid", order.getOrderNo());
        map.put("callbackurl", HOST + "/notify/yiaiNotify");
        String sign = DigestUtils.md5Hex(SignUtils.params(map) + business.getSecretKey());
        map.put("agent", "");
        map.put("payerIp", order.getPayerIp());
        map.put("sign", sign);
        String receive = HttpUtils.post("http://pay.55555pay.com/chargebank.aspx ", HttpUtils.formatData(map));
        String reason = "";
        try {
            String code;
            Document document = Jsoup.parse(receive);
            if (PayTypeDict.WX_H5.equals(order.getPayType())) {
                Elements a = document.getElementsByTag("a");
                code = a.attr("href");
            } else {
                Element qRcode = document.getElementById("QRcode");
                String src = qRcode.attr("src");
                code = src.replace("http://qr.liantu.com/api.php?text=", "");//提取真正的支付地址
                code = code.replace("http://pan.baidu.com/share/qrcode?w=280&h=280&url=", "");//提取真正的支付地址
                code = URLDecoder.decode(code);
            }
            if (StringUtils.isEmpty(code)) {
                reason = "二维码获取失败";
                throw new BaseException();
            }
            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(code);
            model.setRespCode("1");
            model.setRespInfo("成功");

            order.setCode(code);
            orderService.save(order);
            return;
        } catch (Exception e) {
            PayFailed payFailed = new PayFailed();
            payFailed.setUserId(order.getUserId());
            payFailed.setOutOrderNo(order.getOutOrderNo());
            payFailed.setReason(reason);
            payFailed.setContent(receive);
            payFailed.setParams(HttpUtils.formatData(map));
            payFaildService.simpleSave(payFailed);
            model.setRespInfo("失败");
            return;
        }
    }

    public void xjwf(Business business, Order order, RespBody model, String bankCode) {
        Map<String, String> map = new HashMap<String, String>();

        map.put("userid", business.getAccount());
        map.put("bankCode", bankCode);
        map.put("defaultbank", "");
        map.put("returnUrl", "http://baidu.com");
        map.put("amount", "10");
        /**参与验签的字段*/
        String sign = SignUtils.getKeyedDigest(SignUtils.getSignParam(map), business.getSecretKey());
        map.put("orderCode", "xj_gateway");
        map.put("sign", sign);
        map.put("pay_number", String.valueOf(new Date().getTime()));
        map.put("notify_url", HOST + "/notify/xjwfNotify");
        String sr = HttpUtils.post("http://extman.kefupay.cn/pay/pay_mobile.action", HttpUtils.formatData(map));
        Map<String, Object> result = JSON.parseObject(sr, Map.class);
        if ("0000".equals(result.get("respCode"))) {

            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(String.valueOf(result.get("payUrl")));
            model.setRespCode("1");
            model.setRespInfo("成功");
            order.setCode(String.valueOf(result.get("payUrl")));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(result.get("respInfo").toString());
        payFailed.setContent(HttpUtils.formatData(map));
        payFailed.setParams(JSONObject.toJSONString(sr));
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }

    public void xjsmwf(Business business, Order order, RespBody model) {
        Map<String, String> map = new TreeMap<>();
        map.put("userid", business.getAccount());
        map.put("payType", "WXZF");
        map.put("subject", "全宇支付");
        map.put("amount", order.getRealAmount().toString());
        map.put("returnUrl", "http://extman.kefupay.cn/newWechats/test111.action");
        /**参与验签的字段*/
        String sign = SignUtils.params(map);
        sign = DigestUtils.md5Hex(sign + business.getSecretKey());
        map.put("orderCode", "xj_codePay");
        map.put("sign", sign);
        map.put("pay_number", order.getOrderNo());
        map.put("notify_url", HOST + "/notify/xjwfNotify");
        String body = SignUtils.params(map);
        String sr = HttpUtils.post("http://extman.kefupay.cn/pay/pay_mobile.action", body);
        log.info(sr);
        Map<String, Object> result = JSON.parseObject(sr, Map.class);
        if ("000000".equals(result.get("respCode"))) {

            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(String.valueOf(result.get("payUrl")));
            model.setRespCode("1");
            model.setRespInfo("成功");
            order.setCode(String.valueOf(result.get("payUrl")));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(result.get("respInfo").toString());
        payFailed.setContent(sr);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }

    public void xjkjwf(Business business, Order order, RespBody model) {
        Map<String, String> map = new HashMap<>();
        map.put("userid", business.getAccount());
        map.put("amount", order.getRealAmount().toString());
        map.put("returnUrl", "http://extman.kefupay.cn/newWechats/test111.action");
        /**参与验签的字段*/
        String sign = SignUtils.getKeyedDigest(SignUtils.getSignParam(map), business.getSecretKey());
        map.put("orderCode", "xj_quickPay");
        map.put("sign", sign);
        map.put("pay_number", String.valueOf(new Date().getTime()));
        map.put("notify_url", HOST + "/notify/xjwfNotify");
        String body = HttpUtils.formatData(map);
        String sr = HttpUtils.post("http://extman.kefupay.cn/pay/pay_mobile.action", body);
        Map<String, String> result = JSON.parseObject(sr, Map.class);
        if ("000000".equals(result.get("respCode"))) {
            String longUrl = URLEncoder.encode(result.get("payUrl"));
            String shortUrl = HttpUtils.get("http://suo.im/api.php?url=" + longUrl);
            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(shortUrl);
            model.setRespCode("1");
            model.setRespInfo("成功");
            order.setCode(shortUrl);
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(result.get("respInfo"));
        payFailed.setContent(sr);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }


    public void wjxjksm(Business business, Order order, RespBody model) {
        Map<String, String> map = new TreeMap<>();
        if (order.getPayType().equals(PayTypeDict.WX_CODE)) {
            map.put("channel", "100");
        } else if (order.getPayType().equals(PayTypeDict.QQ)) {
            map.put("channel", "200");
        } else {
            map.put("channel", "300");
        }
        map.put("product_name", "商品名称");
        map.put("amount", order.getRealAmount().toString());
        map.put("notifyUrl", HOST + "/notify/wjxjksmNotify");
        map.put("attach", "附加信息");
        map.put("userid", business.getAccount());
        /**参与验签的字段*/
        String sign = SignUtils.params(map);
        sign = DigestUtils.md5Hex(sign + business.getSecretKey());
        map.put("orderCode", "jxjk_scanPay");
        map.put("sign", sign);
        map.put("pay_number", order.getOrderNo());
        String body = SignUtils.params(map);
        String sr = HttpUtils.post("http://extman.kefupay.cn/pay/pay_mobile.action", body);
        log.info(sr);
        Map<String, String> result = JSON.parseObject(sr, Map.class);
        if ("SUCCESS".equals(result.get("respCode"))) {

            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(String.valueOf(result.get("code_url")));
            model.setRespCode("1");
            model.setRespInfo("成功");
            order.setCode(String.valueOf(result.get("code_url")));
            order.setUpOrderNo(result.get("orderId"));
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(result.get("respInfo").toString());
        payFailed.setContent(sr);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }

    public void wxpcsm(Business business, Order order, RespBody model) {


//        final String id = "1721";
//        final String key = "dcb6a325a64346da9d5f2c1906fe6880";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("parter", business.getAccount());
        map.put("type", "1004");
        map.put("value", order.getRealAmount().toString());
        map.put("orderid", order.getOrderNo());
        map.put("callbackurl", HOST + "/notify/yiaiNotify");
        String sign = DigestUtils.md5Hex(SignUtils.params(map) + business.getSecretKey());
        map.put("agent", "");
        map.put("sign", sign);
        String receive = HttpUtils.post("http://pay.55555pay.com/chargebank.aspx ", HttpUtils.formatData(map));
        String url = "<img src=\".*?\" id=\"QRcode\" class=\"qrcode\" alt=\"二维码\" />";//提取html代码中的img中代码
        Pattern pt = Pattern.compile(url);
        Matcher mt = pt.matcher(receive);
        String url2 = "";
        while (mt.find()) { //得到img代码
            url2 = mt.group();
            System.out.println("得到的数据：" + mt.group());
        }
        String role = "weixin://.*?\"";//提取真正的支付地址
        Pattern pt2 = Pattern.compile(role);
        Matcher mt2 = pt2.matcher(url2);
        String result2 = "";
        while (mt2.find()) {
            String[] result = mt2.group().split("\"");
            for (int a = 0; a < result.length; a++) {
                result2 = result2 + result[a];
            }
        }
        String realPayUrl = UrlUtils.getURLDecoderString(result2);//支付地址URL解码
        if (realPayUrl.indexOf("weixin:") == 0) {
            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(realPayUrl);
            model.setRespCode("1");
            model.setRespInfo("成功");

            order.setCode(realPayUrl);
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(result.get("respInfo").toString());
        payFailed.setContent(HttpUtils.formatData(map));
        payFailed.setParams(JSONObject.toJSONString(receive));
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }

    public void zfbpcsm(Business business, Order order, RespBody model) {


//        final String id = "1721";
//        final String key = "dcb6a325a64346da9d5f2c1906fe6880";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("parter", business.getAccount());
        map.put("type", "992");
        map.put("value", order.getRealAmount().toString());
        map.put("orderid", order.getOrderNo());
        map.put("callbackurl", HOST + "/notify/yiaiNotify");
        String sign = DigestUtils.md5Hex(SignUtils.params(map) + business.getSecretKey());
        map.put("agent", "");
        map.put("sign", sign);
        String receive = HttpUtils.post("http://pay.55555pay.com/chargebank.aspx ", HttpUtils.formatData(map));
        String url = "<img src=\".*?\" id=\"QRcode\" class=\"qrcode\" alt=\"二维码\" />";//提取html代码中的img中代码
        Pattern pt = Pattern.compile(url);
        Matcher mt = pt.matcher(receive);
        String url2 = "";
        while (mt.find()) { //得到img代码
            url2 = mt.group();
            System.out.println("得到的数据：" + mt.group());
        }
        String role = "http://.*?\"";//提取真正的支付地址
        Pattern pt2 = Pattern.compile(role);
        Matcher mt2 = pt2.matcher(url2);
        String result2 = "";
        while (mt2.find()) {
            String[] result = mt2.group().split("\"");
            for (int a = 0; a < result.length; a++) {
                result2 = result2 + result[a];
            }
        }
        String realPayUrl = UrlUtils.getURLDecoderString(result2);//支付地址URL解码
        if (realPayUrl.indexOf("https") > 0) {
            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(realPayUrl);
            model.setRespCode("1");
            model.setRespInfo("成功");

            order.setCode(realPayUrl);

            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(result.get("respInfo").toString());
        payFailed.setContent(HttpUtils.formatData(map));
        payFailed.setParams(JSONObject.toJSONString(receive));
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }

    public void smzf1(Business business, Order order, RespBody model) {
        String orderNo = order.getOrderNo();
        // 调整订单号长度
        if (orderNo.length() > 32) {
            orderNo = orderNo.substring(orderNo.length() - 29, orderNo.length());
            orderNo = order.getUserId() + orderNo;
            order.setOrderNo(orderNo);
            try {
                orderService.save(order);
            } catch (Exception e) {
                model.setRespInfo("下单失败，请重新下单");
                return;
            }
        }
        Date date = new Date();
        SortedMap<String, String> map = new TreeMap<>();
        map.put("out_trade_no", order.getOrderNo());
        String amount = order.getRealAmount().toString();
        map.put("total_fee", order.getRealAmount().multiply(new BigDecimal(100)).setScale(0).toString());
        map.put("mch_create_ip", "127.0.0.1");
        if (order.getPayType().equals(PayTypeDict.ALI_CODE) || order.getPayType().equals(PayTypeDict.ALI_WAP))
            map.put("service", "pay.alipay.native");
        else if (order.getPayType().equals(PayTypeDict.WX_CODE))
            map.put("service", "pay.weixin.native");
        map.put("mch_id", business.getAccount());
        map.put("body", "body");
        map.put("notify_url", HOST + "/notify/smzf1Notify");
        map.put("nonce_str", String.valueOf(date.getTime()));

        String sign = SignUtils.sign(map, business.getSecretKey());
        map.put("sign", sign);

        String reqUrl = "https://pay.swiftpass.cn/pay/gateway";
        String body = XmlUtils.parseXML(map);
        log.info("reqParams:" + body);
        String res = HttpUtils.post(reqUrl, body);
        log.info(res);
        Map<String, String> resultMap = null;
        try {
            resultMap = XmlUtils.toMap(res.getBytes(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("下单失败");
        }
        if ("0".equals(resultMap.get("result_code"))) {
            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(resultMap.get("code_url"));
            model.setRespCode("1");
            model.setRespInfo("成功");
            order.setCode(resultMap.get("code_url"));

            orderService.save(order);

            return;
        }

        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
        payFailed.setReason(resultMap.get("message"));
        payFailed.setContent(res);
        payFailed.setParams(body);
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }

//    public void ghtsm(Business business, Order order, RespBody model) {
//        String key = business.getSecretKey();
//        String userId = business.getAccount();
//        Date date = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
//        String version = "V2.0";
//
//        String orderNo = order.getOrderNo();
//        ChinaInPayCodeRequest chinaInPayCodeRequest = new ChinaInPayCodeRequest();
//        chinaInPayCodeRequest.setBgUrl(HOST + "/notify/ghtsmNotify");
//        chinaInPayCodeRequest.setCurCode("CNY");
//        chinaInPayCodeRequest.setOrderAmount(order.getRealAmount().multiply(new BigDecimal(100)).toString());
//        chinaInPayCodeRequest.setOrderSource("1");
//        chinaInPayCodeRequest.setOrderTime(sdf.format(date));
//        chinaInPayCodeRequest.setService("getCodeUrl");
//        chinaInPayCodeRequest.setMerchantNo(userId);
//        chinaInPayCodeRequest.setVersion(version);
//        chinaInPayCodeRequest.setOrderNo(orderNo);
//        if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
//            chinaInPayCodeRequest.setPayChannelCode("CX_WX");
//        } else if (PayTypeDict.ALI_CODE.equals(order.getPayType()) || PayTypeDict.ALI_WAP.equals(order.getPayType())) {
//            chinaInPayCodeRequest.setPayChannelCode("CX_ZFB");
//        }
//        Map<String, String> map = new HashMap<>();
//        try {
//            map = BeanToMapUtil.convertBean(chinaInPayCodeRequest);
//        } catch (IntrospectionException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
//
//        map.remove("key");
//        map.remove("url");
//        map.remove("sign");
//        SignUtils.removeNull(map);
//        String sign = PaixuSign.getSign(map, key);
//        map.put("sign", sign);
//        String receive = null;
//        try {
//            receive = HttpClientUtil.post("http://service.gaohuitong.com/PayApi/nativePay", map);
//            log.info(receive);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BaseException();
//        }
//        Map<String, String> result = JSON.parseObject(receive, Map.class);
//        if ("10000".equals(result.get("dealCode"))) {
//            order.setStatus(StatusDict.WAIT_PAY);
//            model.setBody(result.get("codeUrl"));
//            model.setRespCode("1");
//            model.setRespInfo("成功");
//
//            order.setCode(result.get("codeUrl"));
//            orderService.save(order);
//            return;
//        }
//        PayFailed payFailed = new PayFailed();
//        payFailed.setUserId(order.getUserId());
//        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(result.get("dealMsg"));
//        payFailed.setContent(receive);
//        payFailed.setParams(JSON.toJSONString(map));
//        payFaildService.simpleSave(payFailed);
//        model.setRespInfo("失败");
//        return;
//    }

//    public void easyPay(Business business, Order order, RespBody model) {
//        log.info("invoke easyPay method....");
//        ApiClient apiClient = ApiClientFactory.newClient("https://gw.ak47pay.com/native/", "ZFCK24000JAXS", "2017102821494327000");
//        ApiRequestBuilder builder = ApiRequestBuilder.newInstance("com.opentech.cloud.easypay.trade.create", "0.0.1");
//        builder.addParameter("merchantNo", "ZFCK24000JAXS");
//        builder.addParameter("outTradeNo", order.getOrderNo());
//        builder.addParameter("amount", order.getRealAmount().multiply(new BigDecimal(100)).longValue());
//        if (PayTypeDict.WX_CODE.equals(order.getPayType())) {
//            builder.addParameter("payType", "WECHAT_QRCODE_PAY");
//        } else if (PayTypeDict.QQ.equals(order.getPayType()) || PayTypeDict.QQ_WAP.equals(order.getPayType())) {
//            builder.addParameter("payType", "QQ_QRCODE_PAY");
//        } else if (PayTypeDict.CODE_BANK.equals(order.getPayType())) {
//            builder.addParameter("payType", "UNION_PAY_QRCODE_PAY");
//        } else if (PayTypeDict.ALI_CODE.equals(order.getPayType()) || PayTypeDict.ALI_WAP.equals(order.getPayType())) {
//            builder.addParameter("payType", "ALIPAY_QRCODE_PAY");
//        } else if (PayTypeDict.JD.equals(order.getPayType())) {
//            builder.addParameter("payType", "JD_QRCODE_PAY");
//        } else if (PayTypeDict.WX_H5.equals(order.getPayType())) {
//            builder.addParameter("payType", "WECHAT_WAP_PAY");
//        }
//        builder.addParameter("content", "content");
//        builder.addParameter("callbackURL", HOST + "/notify/easyPayNotify");
//        ApiResponse response = apiClient.invoke(builder.build());
//        String res = JSON.toJSONString(response);
//        log.info(res);
//        if (response.isSucceed()) {
//            Map<String, String> map = response.getData(Map.class);
//            order.setStatus(StatusDict.WAIT_PAY);
//            model.setBody(map.get("paymentInfo"));
//            model.setRespCode("1");
//            model.setRespInfo("成功");
//            order.setCode(map.get("paymentInfo"));
//            order.setUpOrderNo(map.get("tradeNo"));
//            orderService.save(order);
//            return;
//        }
//        PayFailed payFailed = new PayFailed();
//        payFailed.setUserId(order.getUserId());
//        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(response.getMsg());
//        payFailed.setContent(res);
//        payFailed.setParams(JSON.toJSONString(builder.build().getParameters()));
//        payFaildService.simpleSave(payFailed);
//        model.setRespInfo("失败");
//        return;
//
//    }

    public void yiaiwxh5(Business business, Order order, RespBody model) {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("parter", business.getAccount());
        map.put("type", "1006");
        map.put("value", order.getRealAmount().toString());
        map.put("orderid", order.getOrderNo());
        map.put("callbackurl", HOST + "/notify/yiaiNotify");
        String sign = DigestUtils.md5Hex(SignUtils.params(map) + business.getSecretKey());
        map.put("agent", "");
        map.put("sign", sign);
        String receive = HttpUtils.post("http://pay.55555pay.com/chargebank.aspx ", HttpUtils.formatData(map));
        String url = "<a href=\".*?\">";//提取html代码中的img中代码
        Pattern pt = Pattern.compile(url);
        Matcher mt = pt.matcher(receive);
        String url2 = "";
        while (mt.find()) { //得到img代码
            url2 = mt.group();
            System.out.println("得到的数据：" + mt.group());
        }
        String role = "https.*?\"";//提取真正的支付地址
        Pattern pt2 = Pattern.compile(role);
        Matcher mt2 = pt2.matcher(url2);
        String result2 = "";
        while (mt2.find()) {
            String[] result = mt2.group().split("\"");
            for (int a = 0; a < result.length; a++) {
                result2 = result2 + result[a];
            }

        }
        String realPayUrl = UrlUtils.getURLDecoderString(result2);//支付地址URL解码
        if (realPayUrl.indexOf("https") >= 0) {
            order.setStatus(StatusDict.WAIT_PAY);
            model.setBody(realPayUrl);
            model.setRespCode("1");
            model.setRespInfo("成功");

            order.setCode(realPayUrl);
            orderService.save(order);
            return;
        }
        PayFailed payFailed = new PayFailed();
        payFailed.setUserId(order.getUserId());
        payFailed.setOutOrderNo(order.getOutOrderNo());
//        payFailed.setReason(result.get("respInfo").toString());
        payFailed.setContent(HttpUtils.formatData(map));
        payFailed.setParams(JSONObject.toJSONString(receive));
        payFaildService.simpleSave(payFailed);
        model.setRespInfo("失败");
        return;
    }

    public void selfZFB(Business business, Order order, RespBody model) {
        int i = 0;
        AliCode aliCode = null;
        order.setRealAmount(new BigDecimal(Math.ceil(order.getRealAmount().doubleValue())));
        while (i < 3) {
            try {
                aliCode = aliCodeService.checkCode(business.getId(), order.getRealAmount());
                if (aliCode != null)
                    break;
                i++;
                Thread.sleep(1000);
            } catch (BaseException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (aliCode == null) {
            int money = order.getRealAmount().intValue();
            if (money <= 1000) {

            } else if (money < 5000) {
                money = money / 100 * 100;
            } else if (money < 10000) {
                money = money / 500 * 500;
            } else {
                model.setRespInfo("最高可下单金额10000元");
                return;
            }
            model.setRespInfo("距离最近的可下单金额为" + money + "元，请重新下单" + money + "元");
            return;
        }

//        if (aliCode == null) {
//            model.setRespInfo("暂无可用二维码");
//            return;
//        }
        order.setCodeId(aliCode.getId());
        order.setRemark(aliCode.getRemark());
        String qrcode = HOST + "/v2/selfPay/" + order.getId();
//        String qrcode = aliCode.getQrCode();
//        order.setStatus(StatusDict.WAIT_PAY);
        order.setCode(qrcode);
        model.setBody(qrcode);//读取二维码内容
        model.setRespCode("1");
        model.setRespInfo("成功");
        orderService.save(order);
    }

    private void selfZFB2(Business business, Order order, RespBody model) {

        int i = 0;
        AliCode2 aliCode = null;
        order.setRealAmount(new BigDecimal(Math.ceil(order.getRealAmount().doubleValue())));
        while (i < 3) {
            try {
                aliCode = aliCode2Service.checkCode(business.getId(), order.getRealAmount());
                if (aliCode != null)
                    break;
                i++;
                Thread.sleep(1000);
            } catch (BaseException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (aliCode == null) {
            int money = order.getRealAmount().intValue();
            if (money <= 1000) {

            } else if (money < 5000) {
                money = money / 100 * 100;
            } else if (money < 10000) {
                money = money / 500 * 500;
            } else {
                model.setRespInfo("最高可下单金额10000元");
                return;
            }
            model.setRespInfo("距离最近的可下单金额为" + money + "元，请重新下单" + money + "元");
            return;
        }

        order.setRealAmount(new BigDecimal(aliCode.getRemark()));
        order.setCodeId(aliCode.getId());
        order.setRemark(aliCode.getRemark());
        String qrcode = HOST + "/v2/selfPay/" + order.getId();
//        String qrcode = aliCode.getQrCode();
//        order.setStatus(StatusDict.WAIT_PAY);
        order.setCode(qrcode);
        model.setBody(qrcode);//读取二维码内容
        model.setRespCode("1");
        model.setRespInfo("成功");
        orderService.save(order);
    }

    private String toShort(String receive) {
        String longUrl = URLEncoder.encode(receive);
        String shortUrl = HttpUtils.get("http://suo.im/api.php?url=" + longUrl);
        return shortUrl;
    }

}
